function DefaultDataFactory(mask) {
    var me = this;
    this.areaMap = null;
    this.areaList1 = null;
    this.areaList2 = null;
    this.wsResult = null;
    this.xsResults = null;
    this.fqResults = null;
    this.fqData = null;
    this.getDefaultData= function () {
        var def = $.Deferred();
        var url = "/jsite-szy-dispatch/a/szy/dispatch/waterAllocation/default?proCd=" + $.dispatch.getProCd() +
        '&type=' + $.dispatch.getDtype();
        $.getJSON(url, function (data) {
            if (data) {
                me.wsResult = data.wsResult;
                me.xsResults = data.xsResults;
                me.fqResults = data.fqResults;
            } else {
                Ext.Msg.alert("提示信息", "数据缺失，请检查前几步数据是否保存!");
            }
            def.resolve();
        })
        .fail(function() { 
            Ext.Msg.alert("提示信息", "数据获取失败!");
        });
        return def.promise();
    }
    this.getFqData = function () {
        var def = $.Deferred();
        $.getJSON("/jsite-szy-dispatch/a/szy/dispatch/fqData", function (data) {
            me.fqData = data;
            me.formatFqData();
            def.resolve();
        })
        .fail(function() { 
            Ext.Msg.alert("提示信息", "数据获取失败!");
        });
        return def.promise();
    }
}

DefaultDataFactory.prototype = {
    formatFqData: function () {
        var me =this;
        var map = {};
        var list1 = [];
        var list2 = [];
        $.each(me.fqData, function (index, obj) {
            list1.push({
                adCd: obj.adCd,
                adNm: obj.adNm
            });
            $.merge(list2, obj.waList);
            var tempList = [];
            $.each(obj.waList, function (index2, obj2) {
                tempList.push(obj2.wrcsCd);
            });
            map[obj.adCd] = tempList;
        });
        me.areaMap = map;
        me.areaList1 = list1;
        me.areaList2 = list2;
    },
    getTotalData: function () {
        var me = this;
        var areaList1 = this.areaList1;
        var fqMap = this.areaMap;
        var r1 = this.xsResults;
        var r2 = this.fqResults;
        var rData = [];
        for (var adCd in fqMap) {
            var total1 = 0, total2 = 0;
            var regCdList = fqMap[adCd];
            $.each(regCdList, function (index1, regCd) {
                var tempR1 = $.grep(r1, function (obj2, index2) {
                    return obj2.regCd === regCd;
                });
                var tempR2 = $.grep(r2, function (obj3, index3) {
                    return obj3.regCd === regCd;
                });
                total1 += me.sumItmes(tempR1, 'totWat');
                total2 += me.sumItmes(tempR2, 'totRs');
            });
            rData.push({
                adCd: adCd, 
                total1: me.numberToFixed(total1), 
                total2: me.numberToFixed(total2)
            });
        }
        return rData;
    },
    selectByAdCdAndArea: function (adCd) {
        var me = this;
        var r1 = this.xsResults;
        var r2 = this.fqResults;
        var regCdList = this.areaMap[adCd];
        var rData = [];
        $.each(regCdList, function (index1, regCd) {
            var tempR1 = $.grep(r1, function (obj2, index2) {
                return obj2.regCd === regCd;
            });
            var tempR2 = $.grep(r2, function (obj3, index3) {
                return obj3.regCd === regCd;
            });
            var t = {};
            t.regCd = regCd;
            $.each(tempR1, function (index4, row1) {
                var month1 = row1.month;
                t['a' + month1] = row1.totWat;
            });
            $.each(tempR2, function (index5, row2) {
                var month2 = row2.month;
                t['b' + month2] = row2.totRs;
            });
            rData.push(t);
        });
        return rData;
    },
    selectByAdCdAndType: function (adCd) {
        const type1Fields = ['dWat', 'uWat', 'bhWat', 'shWat', 'pwirWat', 'pdirWat', 'pvirWat', 
        'fiWat', 'aiWat', 'fishWat', 'indWat', 'nindWat'];
        const type2Fields = ['drs', 'urs', 'bhRs', 'shRs', 'pwirRs', 'pdirRs', 'pvirRs', 
        'fiRs', 'aiRs', 'mfishRs', 'indRs', 'nindRs'];
        const typeVals = ['城镇居民', '农村居民', '大牲畜', '小牲畜', '水田', '水浇地', '菜田', 
        '林果地', '草场', '鱼塘', '火核', '非火核'];
        var me = this;
        var r1 = this.xsResults;
        var r2 = this.fqResults;
        var regCdList = this.areaMap[adCd];
        var rData = [];
        var tempR1 = $.grep(r1, function (obj2, index2) {
            return $.inArray(obj2.regCd, regCdList) !== -1;
        });
        var tempR2 = $.grep(r2, function (obj3, index3) {
            return $.inArray(obj3.regCd, regCdList) !== -1;
        });
        var mergeData = me.mergeRegData(tempR1, tempR2);
        var p1 = me.parseAreaToTypeData(mergeData.m1, type1Fields, typeVals, 'a');
        var p2 = me.parseAreaToTypeData(mergeData.m2, type2Fields, typeVals, 'b');
        $.each(p1, function (index4, obj4) {
            $.each(p2, function (index5, obj5) {
                if (obj4.type === obj5.type) {
                    $.extend(obj4, obj5);
                }
            });
        });
        return p1;
    },
    parseAreaToTypeData: function (data, fields, typeVals, type) {
        var rData = [];
        var me = this;
        $.each(fields, function (index1, val1) {
            var t = {};
            t.type = typeVals[index1];
            var total = 0;
            $.each(data, function (index2, obj1) {
                var month = obj1.month;
                var v = obj1[val1];
                total += v;
                t[type + month] = v;
            });
            t[type + 'total'] = me.numberToFixed(total);
            rData.push(t);
        });
        return rData;
    },
    mergeRegData: function (data1, data2) {
        var me = this;
        var mergeList1 = [];
        var mergeList2 = [];
        for (var i = 1; i <= 12; i++) {
            var monthData1 = $.grep(data1, function (obj1, index1) {
                return obj1.month === i;
            });
            var monthData2 = $.grep(data2, function (obj2, index2) {
                return obj2.month === i;
            });
            var tm1 = {};
            var tm2 = {};
            tm1.month = i;
            tm2.month = i;
            $.each(monthData1, function (index5, obj5) {
                for (var key1 in obj5) {
                    if (key1 !== 'month' && key1 !== 'regCd') {
                        if (!tm1.hasOwnProperty(key1)) {
                            tm1[key1] = 0;
                        }
                        tm1[key1] += obj5[key1];
                    }
                }
            });
            $.each(monthData2, function (index6, obj6) {
                for (var key2 in obj6) {
                    if (key2 !== 'month' && key2 !== 'regCd') {
                        if (!tm2.hasOwnProperty(key2)) {
                            tm2[key2] = 0;
                        }
                        tm2[key2] += obj6[key2];
                    }
                }
            });
            me.fixObjectNum(tm1);
            me.fixObjectNum(tm2);
            mergeList1.push(tm1);
            mergeList2.push(tm2);
        }
        return {
            m1: mergeList1, m2: mergeList2
        };
    },
    fixObjectNum: function (data) {
        var me = this;
        for (var key in data) {
            if (typeof data[key] === 'number') {
                data[key] = me.numberToFixed(data[key]);
            }
        }
    },
    numberToFixed: function (number, fix) {
        return parseFloat(number.toFixed(fix || 1));
    },
    sumItmes: function (data, totalField) {
        var total = 0;
        $.each(data, function (index, obj) {
            total += obj[totalField];
        });
        return parseFloat(total.toFixed(1));
    }
}

Ext.define('Admin.view.needWater.waterAllocation.WaterAllocationController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.waterAllocationController',
    views: ['Admin.view.needWater.waterAllocation.WaterAllocation'],
    beforeRender: function () {
        this.showNum = 0;
    },
    showPage: function () {
        var me = this;
        me.showNum++;
        if (me.showNum >= 1) {
            var myMask = new Ext.LoadMask($.dispatch.componentQuery('waterAllocation'), { 
                msg: "正在加载数据..." 
            });
            myMask.show();
            me.myMask = myMask;
            me.df = new DefaultDataFactory();
            $.when(me.df.getDefaultData(), me.df.getFqData())
            .then(function () {
                myMask.hide();
                me.setGridData();
            });
            me.initWidget();
        }
    },
    setGridData: function () {
        var me = this;
        Ext.data.StoreManager.lookup('wa_store1').setData([]);
        Ext.data.StoreManager.lookup('wa_store2').setData([]);
        Ext.data.StoreManager.lookup('wa_store3').setData([]);
        var data1 = me.df.getTotalData();
        me.setTotalText(data1);
        Ext.data.StoreManager.lookup('wa_store1').setData(data1);
        var grid0 = me.lookupReference('grid0');
        grid0.getSelectionModel().select(0);
        me.changeArea(grid0, data1[0].adCd);
    },
    setTotalText: function (data) {
        var total = 0;
        $.each(data, function (index, obj) {
            total += obj.total1;
        });
        var totalStr = (total / 10000).toFixed(1);
        $(this.lookupReference('waText').body.dom).find('#waMaxSl').html(this.df.wsResult.maxSl);
        $(this.lookupReference('waText').body.dom).find('#waTotRs').html(totalStr);
    },
    changeArea: function (_grid, _selectRrow) {
        var me = this;
        // var selectRow = me.lookupReference('areaGrid').getSelectionModel().getSelected();
        var adCd = typeof _selectRrow === 'string' ? _selectRrow : _selectRrow.get('adCd');;
        var data1 = me.df.selectByAdCdAndArea(adCd);
        var data2 = me.df.selectByAdCdAndType(adCd);
        Ext.data.StoreManager.lookup('wa_store2').setData(data1);
        Ext.data.StoreManager.lookup('wa_store3').setData(data2);
    },
    saveOrUpdate: function (mask) {
        var me = this;
        // var myMask = new Ext.LoadMask($.dispatch.componentQuery('waterAllocation'), { 
        //     msg: "正在保存..." 
        // });
        // myMask.show();
        var url = '/jsite-szy-dispatch/a/szy/dispatch/waterAllocation/saveOrUpdate?proCd=' + $.dispatch.getProCd() + 
        '&type=' + $.dispatch.getDtype();
        $.ajax({
            url: url,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(me.df.fqResults)
        })
        .done(function(res) { 
            if (res) {
                Ext.Msg.alert("提示信息", "保存成功！");
            }
        })
        .fail(function() { 
            Ext.Msg.alert("提示信息", "保存失败！");
        })
        .always(function () {
            mask.hide();
        })
    },
    allocationCalc: function () {
        var me = this;
        var myMask = new Ext.LoadMask($.dispatch.componentQuery('waterAllocation'), { 
            msg: "正在分配..." 
        });
        myMask.show();
        var data = {
            wsResult: me.df.wsResult,
            xsResults: me.df.xsResults,
            fqResults: me.df.fqResults
        };
        var url = '/jsite-szy-dispatch/a/szy/dispatch/waterAllocation/clac';
        $.ajax({
            url: url,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data)
        })
        .done(function(data) {
            me.df.wsResult = data.wsResult;
            me.df.xsResults = data.xsResults;
            me.df.fqResults = data.fqResults;
            me.setGridData();
            me.saveOrUpdate(myMask);
        })
        .fail(function() { 
            Ext.Msg.alert("提示信息", "分配失败！");
        })
    },
    // 转换 用水区域 编号为名称
    formatAdCdToName: function (value) {
        var data = this.df.areaList1;
        var name = '';
        $.each(data, function (index, obj) {
            if (value === obj.adCd) {
                name = obj.adNm;
                return false;
            }
        });
        return name;
    },
    // 转换 用水单元 编号为名称
    formatRegCdToName: function (value) {
        var data = this.df.areaList2;
        var name = '';
        $.each(data, function (index, obj) {
            if (value === obj.wrcsCd) {
                name = obj.wrcsNm;
                return false;
            }
        });
        return name;
    },
    initWidget: function () {
        var me = this;
        me.resizePanel();
        window.onresize = function () {
            me.resizePanel();
        };
    },
    resizePanel: function () {
        var me = this;
        var container = me.getView();
        container.setHeight(document.documentElement.clientHeight - 95);
    },
    renderReduction: function (v, m, r) {
        var num = m.column.dataIndex.split('c')[1];
        var val1 = r.data['a' + num];
        var val2 = r.data['b' + num];
        var reduction = 0;
        if (val2 !== 0 && val1 !== 0) {
            reduction = parseFloat((100 - (val1 * 100 / val2)).toFixed(2));
        }
        var color = '#333333';
        if (reduction > 0) {
            color = '#FF0000';
        } else if (reduction === 0) {
            color = '#333333';
        } else if (reduction < 0) {
            color = '#FF0000';
        }
        return '<span style="color: ' + color + '">' + reduction + '</span>';
    },
    renderColor: function (_value) {
        var parseNum = parseFloat(_value);
        
    }
})
